from requests import post, get
# import requests
from re import findall
from time import sleep
from json import dumps

def update_or_not(old_version):
    request_url = "https://gitee.com/Setless7/PathOfTrade/tree/master/ValueSearch/release_version"
    res = get(request_url)
    sleep(0.6)
    new_version = findall(r'pathoftrade_([v0-9_]*).rar', res.text)[0]
    new_version = new_version.replace('_', '.')
    print(new_version)
    return old_version == new_version

class decoder:
    def __init__(self):
        self.searcher = searcher()
        self.equipment_list = [
            '箭袋', '胸甲', '鞋子', '戒指', '项链', '腰带', '弓', '战杖', '长杖',
            '匕首', '单手剑', '单手斧', '单手锤', '法杖', '爪', '短杖', '符文匕首', '细剑',
            '双手剑', '双手斧', '双手锤', '盾', '魔符', '功能药剂', '生命药剂', '魔力药剂', '复合药剂'
        ]

    def decode_and_search(self, target_str):
        print("decode_and_search")
        print(target_str)
        target_str = target_str.replace('\r', '')
        items = target_str.split('\n')

        price_list = []
        ObjectKinds = {'符': 'accessory.amulet', '带': 'accessory.belt', '指': 'accessory.ring',
                       '冠': 'armour.helmet', '盔': 'armour.helmet', '兜': 'armour.helmet', '帽': 'armour.helmet',
                       '面': 'armour.helmet', '冠': 'armour.helmet', '环': 'armour.helmet',
                       '手': 'armour.gloves', '手套': 'armour.gloves', '套': '',
                       '心': 'armour.chest', '外套': 'armour.chest', '衣': 'armour.chest', '袍': 'armour.chest',
                       '甲': 'armour.chest', '铠': 'armour.chest', '装': 'armour.chest',
                       '胫甲': 'armour.boots', '鞋': 'armour.boots', '靴': 'armour.boots',
                       }
        if '星团珠宝' in target_str:
            print("星团珠宝")
            if '天神之音' in target_str:
                pricenum = int(findall('增加 ([1-9]) 个无特殊效果的小天赋', '\n'.join(items))[0])
                payloadList = {
                    "query": {
                        "status": {
                            "option": "any"
                        },
                        "name": "天神之音",
                        "type": "大型星团珠宝",
                        "stats": [{
                            "type": "and",
                            "filters": [{
                                "id": "explicit.stat_1085446536",
                                "value": {
                                    "min": pricenum,
                                    "max": pricenum
                                },
                                "disabled": 0
                            }]
                        }]
                    },
                    "sort": {"price": "asc"}
                }
                return "暂不支持"
            elif '妄想症' not in target_str:
                return "暂不支持"

        if '蓝珠宝' in target_str or '红珠宝' in target_str or '绿珠宝' in target_str:
            print("黄珠宝")
            return "暂不支持"

        if "异界地图" in target_str:
            if '稀 有 度: 普通' in target_str or '稀 有 度: 魔法' in target_str:
                price_list = self.map_solve_normal(target_str)
            else:
                price_list = self.map_solve(target_str, '完整')
            return price_list

        if "地图碎片" in target_str:
            price_list = self.map_solve(target_str, '碎片')
            return price_list

        if '稀 有 度: 传奇' in target_str:
            print("传奇物品")
            match = False
            for eq in self.equipment_list:
                if eq in target_str:
                    match = True
                    break
            if match:
                types = items[3]
                name = items[2]
                price_list = self.searcher.search(types, name)
                return price_list

        if "预言之力" in target_str:
            print("预言")
            name = items[2].split('/')[0]
            types = "预言"
            price_list = self.searcher.search(types, name)
            return price_list

        if '物品类别: 命运卡' in target_str:
            print("命运卡")
            types = items[2].split('[')[0]
            price_list = self.searcher.search(types)
            return price_list

        if '稀 有 度: 宝石' in target_str:
            print("宝石")
            types = items[2].split('[')[0]
            print(types)
            kind = 2
            gemLevel = items[5].split()[1][0:2]
            print("gemLevel %s" % gemLevel)
            price_list = self.searcher.search(types, kind=kind, gem_level=gemLevel)
            return price_list

        return "暂不支持"

    def map_solve_normal(self, target_str):
        print("map_solve_normal")

        items = target_str.split('\n')
        if "地图" in items[2]:
            items[2] = ' '.join(items[2].split()[0:-1])
        types = items[2].split('的')[-1].split('之')[-1].split()[0].split(':')[-1]
        kind = 1
        if len(types) == 1:
            # 熔岩之湖等地图
            types = items[2][-4:]
        elif types == '菌潮':
            types = items[2].split('的')[-1].split('之')[-1].split()[1].split(':')[-1]
            kind = 4
        # types = items[1].split('的')[-1].split('之')[-1].split()[1].split(':')[-1]
        level = items[4].split()[1]
        price_list = self.searcher.search(types, kind=kind, map_level=level)
        return price_list

    def map_solve(self, target_str, map_kind):
        items = target_str.split('\n')
        if map_kind == "碎片":
            print("map_solve碎片")
            types = items[2].split('[')[0]
            if types[0:2] == '奴役' or types[0:2] == '压迫' or types[0:2] == '灭绝' or types[0:2] == '清算':
                types = types[0:4]
            elif types[0:2] == '地图':
                types = types.split()[0].split(':')[-1]

            price_list = self.searcher.search(types)
        else:
            print("map_solve完整")
            name = []
            types = items[3].split()[0].split(':')[-1]
            kind = 1
            if types == '菌潮':
                kind = 4
                types = items[3].split()[1].split(':')[-1]
            level = items[5].split()[1]
            if '稀 有 度: 传奇' in target_str:
                kind = 5
                name = items[2].split()[0].split(':')[-1]
            price_list = self.searcher.search(types, name=name, kind=kind, map_level=level)
        return price_list


class searcher:
    def __init__(self) -> None:
        self.postUrl = ''
        self.geturl = ''
        self.season_num = "0"
        self.with_shanhui = False
        self.search_season_information()

    def season(self):
        self.postUrl = 'http://poe.game.qq.com/api/trade/search/S' + self.season_num + '%E8%B5%9B%E5%AD%A3'
        self.geturl = 'http://poe.game.qq.com/trade/search/S' + self.season_num + '%E8%B5%9B%E5%AD%A3'

    # 切换永久区
    def forever(self):
        self.postUrl = 'http://poe.game.qq.com/api/trade/search/%E6%B0%B8%E4%B9%85'
        self.geturl = 'http://poe.game.qq.com/trade/search/%E6%B0%B8%E4%B9%85'

    # 切换闪回区
    def shanhui(self):
        self.postUrl = 'http://poe.game.qq.com/api/trade/search/S' + self.season_num + '%E9%97%AA%E5%9B%9E%E7%8B%82%E6%AC%A2'
        self.geturl = 'http://poe.game.qq.com/trade/search/S' + self.season_num + '%E9%97%AA%E5%9B%9E%E7%8B%82%E6%AC%A2'

    def search_season_information(self):
        request_url = 'http://poe.game.qq.com/trade/search/'
        for _ in range(3):
            res = get(request_url).text
            self.season_num = findall(r'S([0-9]{2})\\u8d5b\\u5b63', res)
            if self.season_num:
                self.season_num = self.season_num[0]
                self.with_shanhui = findall(r'S([0-9]{2})\\u95ea\\u56de', res)
                if self.with_shanhui:
                    self.with_shanhui = True
                else:
                    self.with_shanhui = False
                break
        self.season()

        # 查价函数

    def search(self, types, name=[], kind=0, map_level='1', gem_level='1', money='chaos', payload_list={}):
        print("search")
        for i in range(3):
            listText = self.searchPrice(types, name, kind, map_level, gem_level, money=money,
                                        payloadList=payload_list)
            if listText:
                return listText

        return []

    def searchPrice(self, types, name=[], kind=0, mapLevel='1', gemLevel='1', money='chaos', payloadList={}):
        # payloadData数据
        print("searchPrice")
        if name and kind != 5:
            payloadData = {
                "query": {"status": {"option": "any"}, "type": types, "name": name,
                          "stats": [{"type": "and", "filters": [], "disabled": 0}]},
                "sort": {"price": "asc"}
            }
        elif kind == 1:
            payloadData = {
                "query": {
                    "status": {"option": "any"}, "type": {"option": types, "discriminator": "warfortheatlas"},
                    "stats": [{"type": "and", "filters": [], "disabled": 1}],
                    "filters": {
                        "map_filters": {"filters": {"map_tier": {"min": mapLevel, "max": mapLevel}}, "disabled": 0}}
                },
                "sort": {"price": "asc"}
            }
        elif kind == 2:
            payloadData = {
                "query": {
                    "status": {"option": "any"}, "type": types,
                    "stats": [{"type": "and", "filters": [], "disabled": 1}],
                    "filters": {
                        "misc_filters": {"filters": {"gem_level": {"min": gemLevel, "max": gemLevel}}, "disabled": 0}}
                },
                "sort": {"price": "asc"}
            }
            # filters: {trade_filters: {filters: {price: {min: null, max: null, option: "chaos"}}, disabled: false}}
        elif kind == 3:
            payloadData = {
                "query": {
                    "status": {"option": "any"}, "type": types,
                    "stats": [{"type": "and", "filters": [], "disabled": 1}],
                    "filters": {"trade_filters": {"filters": {"price": {"min": "null", "max": "null", "option": money}},
                                                  "disabled": 0}}
                },
                "sort": {"price": "asc"}
            }
        elif kind == 4:
            payloadData = {
                "query": {
                    "status": {"option": "any"}, "type": {"option": types, "discriminator": "warfortheatlas"},
                    "stats": [{"type": "and", "filters": [], "disabled": 1}],
                    "filters": {"map_filters": {
                        "filters": {"map_tier": {"min": mapLevel, "max": mapLevel}, "map_blighted": {"option": "true"}},
                        "disabled": 0}}
                },
                "sort": {"price": "asc"}
            }
        elif kind == 5:

            payloadData = {
                "query": {
                    "status": {"option": "any"},
                    "type": {"option": types, "discriminator": "warfortheatlas"},
                    "name": {"option": name, "discriminator": "warfortheatlas"},
                    "stats": [{"type": "and", "filters": [], "disabled": 1}],
                    "filters": {
                        "map_filters": {"filters": {"map_tier": {"min": mapLevel, "max": mapLevel}}, "disabled": 0}}
                },
                "sort": {"price": "asc"}
            }
        elif kind == 6:
            payloadData = payloadList
        else:
            payloadData = {
                "query": {"status": {"option": "any"}, "type": types,
                          "stats": [{"type": "and", "filters": [], "disabled": 1}]},
                "sort": {"price": "asc"}
            }
        # 请求头设置

        payloadHeader = {
            'Host': 'poe.game.qq.com',
            'Content-Type': 'application/json',
        }
        try:
            sleep(0.4)
            r = post(self.postUrl, data=dumps(payloadData), headers=payloadHeader)  # 根据请求头获取query ID以及物品ID
            sleep(0.6)
            query_id = findall(r'"id":"([\d\D]*?)"', r.text)  # query ID
            item = findall(r'"result":\[([\d\D]*?)\]', r.text)[0][1:-1].replace('"', '').split(',')  # 物品ID
            request_url = "http://poe.game.qq.com/api/trade/fetch/" + ','.join(item[0:10]) + "?query=" + query_id[0]
            res = get(request_url)
            sleep(0.6)
            text1 = findall(r'"note":"([\d\D]*?)",', res.text)
            if len(item) >= 10:
                request_url = "http://poe.game.qq.com/api/trade/fetch/" + ','.join(item[10:20]) + "?query=" + query_id[
                    0]  # 根据协议以及query ID和物品ID获取物品实际属性（价格，物主ID等...）
                res = get(request_url)
                sleep(0.4)
                text2 = findall(r'"note":"([\d\D]*?)",', res.text)
                text = text1 + text2
            else:
                text = text1
            # text.reverse()
            m = ','.join(text).replace('\\', '').replace('~b', '   ~b')
            text = m.split(',')
            for i in list(range(len(text) - 1, -1, -1)):
                if text[i][0] != '~' and text[i][0] != '=' and text[i][0] != ' ':
                    text.pop(i)
            return text
        except:
            print("error")
            return []


if __name__ == "__main__":
    update_or_not("v1.0")
